package com.thanks.thinkchina.config;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetAddress;

/**
 * @ClassName : SnowflakeConfig
 * @Description : 雪花算法工具
 * @Author : yf.zhu
 * @Date: 2021-06-18 16:35
 */
@Component
@Slf4j
public class SnowflakeConfig {

	@JsonFormat(shape = JsonFormat.Shape.STRING)
	// 为终端ID
	private long workerId = 0;
	//数据中心ID
	private long datacenterId = 14;

	private Snowflake snowflake = IdUtil.createSnowflake(workerId,datacenterId);

	@PostConstruct
	public void init(){
		workerId = NetUtil.ipv4ToLong(InetAddress.getLoopbackAddress().getHostAddress());
		if (StrUtil.isNotBlank(NetUtil.getLocalhostStr())){
			log.info("The localhost of the current machine is：[{}]", NetUtil.getLocalhostStr());
			workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
		}
		log.info("Workid of the current machine:{}",workerId);
	}

	public synchronized long snowflakeId(){
		return snowflake.nextId();
	}

	public synchronized long snowflakeId(long workerId,long datacenterId){
		Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);
		return snowflake.nextId();
	}
}
